<template>
  <div class="history-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>历史记录</span>
          <div class="header-operations">
            <el-button type="primary" @click="refreshData">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operationType" placeholder="请选择操作类型" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="登录" value="LOGIN"></el-option>
            <el-option label="查询" value="QUERY"></el-option>
            <el-option label="新增" value="INSERT"></el-option>
            <el-option label="修改" value="UPDATE"></el-option>
            <el-option label="删除" value="DELETE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="searchForm.username" placeholder="请输入操作人"></el-input>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="historyList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="操作人" width="120" />
        <el-table-column prop="operationType" label="操作类型" width="100">
          <template #default="scope">
            <el-tag
              :type="getOperationTypeTag(scope.row.operationType)"
            >
              {{ getOperationTypeLabel(scope.row.operationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="操作模块" width="120" />
        <el-table-column prop="description" label="操作描述" />
        <el-table-column prop="ip" label="IP地址" width="130" />
        <el-table-column prop="operationTime" label="操作时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="viewDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 详情对话框 -->
      <el-dialog
        v-model="dialogVisible"
        title="操作详情"
        width="700px"
      >
        <div v-if="currentDetail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="操作人">{{ currentDetail.username }}</el-descriptions-item>
            <el-descriptions-item label="操作类型">
              <el-tag :type="getOperationTypeTag(currentDetail.operationType)">
                {{ getOperationTypeLabel(currentDetail.operationType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="操作模块">{{ currentDetail.module }}</el-descriptions-item>
            <el-descriptions-item label="IP地址">{{ currentDetail.ip }}</el-descriptions-item>
            <el-descriptions-item label="操作时间">{{ currentDetail.operationTime }}</el-descriptions-item>
            <el-descriptions-item label="操作描述">{{ currentDetail.description }}</el-descriptions-item>
          </el-descriptions>
          
          <div class="detail-content" v-if="currentDetail.requestParams || currentDetail.responseData">
            <el-tabs>
              <el-tab-pane label="请求参数" v-if="currentDetail.requestParams">
                <pre class="code-block">{{ formatJson(currentDetail.requestParams) }}</pre>
              </el-tab-pane>
              <el-tab-pane label="响应数据" v-if="currentDetail.responseData">
                <pre class="code-block">{{ formatJson(currentDetail.responseData) }}</pre>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  operationType: '',
  username: '',
  startTime: '',
  endTime: ''
})

// 日期范围
const dateRange = ref([])

// 表单引用
const searchFormRef = ref(null)

// 表格数据
const loading = ref(false)
const historyList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const dialogVisible = ref(false)
const currentDetail = ref(null)

// 处理日期变化
const handleDateChange = (val) => {
  if (val) {
    searchForm.startTime = val[0]
    searchForm.endTime = val[1]
  } else {
    searchForm.startTime = ''
    searchForm.endTime = ''
  }
}

// 获取操作类型标签样式
const getOperationTypeTag = (type) => {
  const map = {
    LOGIN: '',
    QUERY: 'info',
    INSERT: 'success',
    UPDATE: 'warning',
    DELETE: 'danger'
  }
  return map[type] || ''
}

// 获取操作类型显示文本
const getOperationTypeLabel = (type) => {
  const map = {
    LOGIN: '登录',
    QUERY: '查询',
    INSERT: '新增',
    UPDATE: '修改',
    DELETE: '删除'
  }
  return map[type] || type
}

// 格式化JSON
const formatJson = (json) => {
  if (typeof json === 'string') {
    try {
      return JSON.stringify(JSON.parse(json), null, 2)
    } catch (e) {
      return json
    }
  }
  return JSON.stringify(json, null, 2)
}

// 获取历史记录列表
const getHistoryList = async () => {
  loading.value = true
  try {
    // 这里应该调用实际的API
    // const res = await getHistoryPage({
    //   ...searchForm,
    //   current: currentPage.value,
    //   size: pageSize.value
    // })
    
    // 模拟数据
    setTimeout(() => {
      historyList.value = [
        {
          id: 1,
          username: 'admin',
          operationType: 'LOGIN',
          module: '系统',
          description: '用户登录',
          ip: '192.168.1.1',
          operationTime: '2023-06-15 10:30:45',
          requestParams: '{"username":"admin","password":"******"}',
          responseData: '{"code":200,"message":"success","data":{"token":"xxx"}}'
        },
        {
          id: 2,
          username: 'admin',
          operationType: 'QUERY',
          module: '用户管理',
          description: '查询用户列表',
          ip: '192.168.1.1',
          operationTime: '2023-06-15 10:35:22',
          requestParams: '{"current":1,"size":10}',
          responseData: '{"code":200,"message":"success","data":{"records":[...]}}'
        },
        {
          id: 3,
          username: 'admin',
          operationType: 'INSERT',
          module: '行业领域',
          description: '新增行业领域',
          ip: '192.168.1.1',
          operationTime: '2023-06-15 11:20:15',
          requestParams: '{"industryDomainId":"tech","industryDomainName":"信息技术"}',
          responseData: '{"code":200,"message":"success","data":true}'
        },
        {
          id: 4,
          username: 'user1',
          operationType: 'UPDATE',
          module: '用户管理',
          description: '修改用户信息',
          ip: '192.168.1.2',
          operationTime: '2023-06-15 14:45:30',
          requestParams: '{"userId":2,"username":"user1","email":"user1@example.com"}',
          responseData: '{"code":200,"message":"success","data":true}'
        },
        {
          id: 5,
          username: 'admin',
          operationType: 'DELETE',
          module: '行业领域',
          description: '删除行业领域',
          ip: '192.168.1.1',
          operationTime: '2023-06-15 16:10:05',
          requestParams: '{"id":3}',
          responseData: '{"code":200,"message":"success","data":true}'
        }
      ]
      total.value = 5
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('获取历史记录失败', error)
    ElMessage.error('获取历史记录失败')
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getHistoryList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getHistoryList()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getHistoryList()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  searchForm.startTime = ''
  searchForm.endTime = ''
  currentPage.value = 1
  getHistoryList()
}

// 刷新数据
const refreshData = () => {
  getHistoryList()
}

// 查看详情
const viewDetail = (row) => {
  currentDetail.value = row
  dialogVisible.value = true
}

// 组件挂载时获取数据
onMounted(() => {
  getHistoryList()
})
</script>

<style scoped>
.history-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  margin-top: 20px;
}

.code-block {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
  overflow: auto;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
  max-height: 400px;
}
</style>